using UnityEngine;
using QFramework;
using System.Collections.Generic;
using System;

namespace ProjectSurviver
{
	public partial class EnemyGenerator : ViewController
	{
		[SerializeField]
		public LevelConfig Config;
		private float mCurrentGenerateSceneds = 0;
		private float mCurrentWaveScends = 0; // 当前波次的时间

		private Queue<EnemyWave> mEnemyWavesQueue = new Queue<EnemyWave>();

		private EnemyWave mCurrentWare = null;

		public int waveCount = 0;

		private int mTotalCount = 0;
		public bool LastWave => waveCount == mTotalCount; // 是否为最后一波

		public EnemyWave currentWave => mCurrentWare;

		public static BindableProperty<int> EnemyCount = new BindableProperty<int>(0); // 敌人数量为0

        void Start()
        {
			foreach (var group in Config.EnemyWaveGroups)
			{
				foreach (var wave in group.Waves)
				{
					// 入队
					mEnemyWavesQueue.Enqueue(wave);
					mTotalCount++;
				}
			}
        }

        void Update()
        {
			if(mCurrentWare == null)
			{
				if(mEnemyWavesQueue.Count > 0)
				{
					waveCount++;
					mCurrentWare = mEnemyWavesQueue.Dequeue();
					mCurrentGenerateSceneds = 0;
					mCurrentWaveScends = 0;
				}
			}

			if(mCurrentWare != null)
			{
				mCurrentGenerateSceneds += Time.deltaTime;
				mCurrentWaveScends += Time.deltaTime;
				if(mCurrentGenerateSceneds >= mCurrentWare.GenerateDuration)
				{
					//置空操作
					mCurrentGenerateSceneds = 0;

					var player = Player.Default;
					if(player)
					{
						var xOry = RandomUtility.Choose(-1, 1);
						var pos = Vector2.zero;
						if(xOry == -1)
						{
							pos.x = RandomUtility.Choose(CameraController.LBTrans.position.x, CameraController.RTTrans.position.x);
							pos.y = RandomUtility.Choose(CameraController.LBTrans.position.y, CameraController.RTTrans.position.y);
						}
						else
						{
							pos.x = RandomUtility.Choose(CameraController.LBTrans.position.x, CameraController.RTTrans.position.x);
							pos.y = RandomUtility.Choose(CameraController.LBTrans.position.y, CameraController.RTTrans.position.y);
						}
						mCurrentWare.EnemyPrefab.Instantiate()
						.Position(pos)
						.Self(self =>
						{
							var enemy = self.GetComponent<IEnemy>();
							enemy.SetSpeedScale(mCurrentWare.SpeedScale);
							enemy.SetHPScale(mCurrentWare.HPScale);
						})
						.Show();
					}
				}

				if(mCurrentWaveScends >= mCurrentWare.scends)
				{
					mCurrentWare = null;
				}
			}
        }
    }
}
